package pl.mchaniewski.ryneczek.web.user;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import pl.mchaniewski.ryneczek.services.PortfolioService;
import pl.mchaniewski.ryneczek.utilities.NavigationUtil;

@Component
@Scope("request")
@PreAuthorize("isAuthenticated()")
public class PortfolioSharesBean {
    private SelectedPortfolioBean selectedPortfolioBean;
    private PortfolioService portfolioService;
    private List<Map<String, Object>> shares;

    @Autowired
    public void setSelectedPortfolioBean(
            SelectedPortfolioBean selectedPortfolioBean) {
        this.selectedPortfolioBean = selectedPortfolioBean;
    }

    @Autowired
    public void setPortfolioService(PortfolioService portfolioService) {
        this.portfolioService = portfolioService;
    }

    @PostConstruct
    public void preInit() {
        if (selectedPortfolioBean.getSelectedPortfolioId() == null) {
            NavigationUtil.directRedirect(NavigationUtil.DIRECT_INDEX);
        }
    }

    public List<Map<String, Object>> getShares() {
        if (shares != null) {
            return shares;
        } else {
            shares = portfolioService
                    .getPortfolioCompaniesInfo(selectedPortfolioBean
                            .getSelectedPortfolio().getPortfolioid());
        }

        return shares;
    }

}
